<template>
  <view class="container">
    <wd-form ref="form" :model="model" :rules="rules">
      <wd-cell-group title="工单信息" border>
        <wd-input
          label="房间/区域"
          label-width="100px"
          v-model="model.roomOrAreaCode"
          :maxlength="20"
          show-word-limit
          prop="roomOrAreaCode"
          required
          clearable
          placeholder="请输入房间/区域"
        />
        <!--    <wd-select-picker
          label="任务类型"
          type="radio"
          filterable
          prop="tasktypeId"
          placeholder="请选择任务类型"
          :show-confirm="false"
          v-model="model.tasktypeId"
          :columns="platformList"
          @change="handelchange"
        />
        <wd-select-picker
          label="任务内容"
          type="radio"
          filterable
          required
          placeholder="请选择任务内容"
          :show-confirm="false"
          v-model="platform"
          :columns="messagelist"
          @change="handelmessagechange"
        />
		 -->
        <wd-picker
          :columns="columns"
          label="任务内容"
          required
          prop="tasktypeId"
          placeholder="请选择任务内容"
          v-model="selectedValue"
          :column-change="onChangeDistrict"
          :display-format="displayFormat"
          @confirm="onConfirm"
        />
        <wd-cell title="紧急" title-width="100px" prop="enmergency" center>
          <view style="text-align: left">
            <wd-switch v-model="model.enmergency" />
          </view>
        </wd-cell>
        <wd-textarea
          v-model="model.content"
          prop="content"
          placeholder="任务内容"
          clearable
          required
        />
      </wd-cell-group>
      <view class="fixed-button">
        <wd-button icon="check" :loading="loading"  @click="send" block>发送</wd-button>
      </view>
    </wd-form>
    <wd-toast />
  </view>
</template>

<script setup lang="ts">
import { ref, onMounted } from 'vue'
import { useUserStore } from '@/store/user'
import { type CreateWorkOrderDto, CodeEnum } from '@/API/order/types'
import { CreateOrder } from '@/API/order/index'
import {
  getalltasktypelist,
  getmessagelistbytypeid
} from '@/API/typemessage/index'
import type {
  SelectParams,
  TaskTypeDto,
  TypeMessageDto
} from '@/API/typemessage/types'
import type { FormRules } from '@/uni_modules/wot-design-uni/components/wd-form/types'
import { useToast } from '@/uni_modules/wot-design-uni'
const loading=ref(false)
const toast = useToast()
const rules: FormRules = {
  roomOrAreaCode: [
    {
      required: true,
      message: '请输入房间/区域'
    }
  ],
  tasktypeId: [
    {
      required: true,
      message: '请选择任务类型'
    }
  ],
  selectedValue: [
    {
      required: true,
      message: '请选择任务类型'
    }
  ],
  // taskmessageId: [
  //   {
  //     required: true,
  //     message: '请选择任务内容'
  //   }
  // ],
  content: [
    {
      required: true,
      message: '请输入内容'
    }
  ]
}

const form = ref()
const model = ref<CreateWorkOrderDto>({
  phonenumber: '',
  roomOrAreaCode: '',
  tasktypeId: '',
  content: '',
  enmergency: false,
  phoneid: ''
})
const platform = ref('')
const platformList = ref<SelectParams[]>([])
const messagelist = ref<SelectParams[]>([])
const typemessagelist = ref<TypeMessageDto[]>([])

const columns = ref<SelectParams[][]>([[]]) // 初始空列
const selectedValue = ref<string[]>([])

onMounted(async () => {
  const tastypes = await getalltasktypelist()
  platformList.value = convertToSelectParams(tastypes)

  const rootData: SelectParams[] = tastypes.map(item => ({
    label: item.name,
    value: item.id,
    disabled: false
  }))
  columns.value = [rootData]
  const messages = await getmessagelistbytypeid(rootData[0].value)
  model.value.tasktypeId = rootData[0].value
  columns.value = [
    columns.value[0],
    messages.map(
      (item): SelectParams => ({
        label: item.message,
        value: item.id,
        disabled: false
      })
    )
  ]

  model.value.content = messages[0].message
})

const onChangeDistrict = async (
  pickerView: any,
  value: SelectParams[],
  columnIndex: number,
  resolve: any
) => {
  const itemvalue = value[columnIndex]
  if (columnIndex === 0) {
    const messages = await getmessagelistbytypeid(itemvalue.value)

    pickerView.setColumnData(
      1,
      messages.map(item => ({
        label: item.message,
        value: item.id,
        disabled: false
      }))
    )

    model.value.tasktypeId = itemvalue.value
  }
  resolve()
}

const onConfirm = (value: any) => {
  model.value.content = value.selectedItems[1].label
}
// 显示格式化
const displayFormat = (items: SelectParams[]) => {
  return items
    .map(item => {
      return item.label
    })
    .join('-')
}

const ToSelectParams = (taskTypes: TypeMessageDto[]): SelectParams[] => {
  return taskTypes.map(message => ({
    value: message.id,
    label: message.title,
    disabled: false // 默认禁用状态为 false
  }))
}

const convertToSelectParams = (taskTypes: TaskTypeDto[]): SelectParams[] => {
  return taskTypes.map(taskType => ({
    value: taskType.id,
    label: taskType.name,
    disabled: false // 默认禁用状态为 false
  }))
}

const handelchange = async ({ value }: { value: string }) => {
  console.log('value', value)
  const messages = await getmessagelistbytypeid(value)
  typemessagelist.value = messages
  messagelist.value = ToSelectParams(messages)
  if (messagelist.value.length > 0) {
    const firstValue = messagelist.value[0].value
    platform.value = firstValue
    //model.value.tasktypeId = firstValue

    const message = typemessagelist.value.find(item => item.id === firstValue)
    model.value.content = message?.message
  }
}
const handelmessagechange = async ({ value }: { value: string }) => {
  const message = typemessagelist.value.find(item => item.id === value)
  model.value.content = message?.message
}

const send = () => {
  form.value
    .validate()
    .then(async ({ valid, errors }: { valid: boolean; errors: string }) => {
      if (valid) {
		  loading.value=true
        const userstore = useUserStore()
        //加判断是否存在phoneid
        model.value.phoneid = userstore.phoneid!
        model.value.ceateUserName = userstore.username
        model.value.phonenumber = userstore.phonenumber
        const result = await CreateOrder(model.value)
        switch (result.code) {
          case CodeEnum.Success:
            toast.success('发送成功')
            break
          case CodeEnum.NoAllocation:
            toast.error('发送失败！未能匹配到分配区域，请检查设置')
            break
          case CodeEnum.NoGroups:
            toast.error('发送失败！未能匹配到分配区域，请检查设置')
            break
          case CodeEnum.NoLogin:
            toast.error('发送失败！无人员在线')
            break
          case CodeEnum.NoRoomArea:
            toast.error('发送失败! 无该房间/区域')
            break
          case CodeEnum.NoTaskType:
            toast.error('发送失败! 无该任务类型')
            break
          case CodeEnum.Error:
            toast.error('发送失败!')
            break
        }
		  loading.value=false
        // console.log(result)
      }
    })
    .catch((error: string) => {
      console.log(error, 'error')
    })
}
</script>

<style lang="scss" scoped>
:deep(.wd-button__text) {
  font-size: 35rpx;
}
.container {
  background: #f8f9fa;

  margin: 30rpx;

  .fixed-button {
  position: fixed;
   bottom: 0;
   left: 0;
   width: 100%;
   background-color: #fff;
   padding: 20rpx 30rpx; /* 增加左右内边距 */
   box-shadow: 0 -4rpx 16rpx rgba(0, 0, 0, 0.06);
   z-index: 999; /* 确保在弹层上方 */
   display: flex;
   justify-content: flex-end;
   gap: 20rpx; /* 按钮间距 */
   /* 适配安全区域 */
   padding-bottom: calc(20rpx + constant(safe-area-inset-bottom));
   padding-bottom: calc(20rpx + env(safe-area-inset-bottom));
  }

  :deep(.group) {
    margin-top: 12px;
  }
}
</style>
